package com.dmz.workflow.util;

import io.reactivex.annotations.CheckReturnValue;

import java.util.Iterator;
import java.util.List;

/**
 * List组合计算方法
 */
class CombinationIterator<T> implements Iterator<T> {

    private int[] _indexArr;

    protected final int _srcSize;

    protected final List<T> source;

    protected StringBuilder _currentValue;

    public CombinationIterator(List<T> source) {
        _currentValue = new StringBuilder();
        this._srcSize = source.size();
        this._indexArr = new int[_srcSize + 2];
        this.source = source;
    }

    @Override
    public boolean hasNext() {
        return _indexArr[_srcSize + 1] != 1;
    }

    @CheckReturnValue
    @Override
    public T next() {
        _currentValue = new StringBuilder();
        for (int index = 1; index <= _srcSize; index++) {
            if (_indexArr[index] == 1) {
                T value = source.get(index - 1);
                if (_currentValue.length() > 0) {
                    _currentValue.append(",");
                }
                _currentValue.append(value);
            }
        }
        int i = 1;
        while (_indexArr[i] == 1) {
            _indexArr[i] = 0;
            i++;
        }
        _indexArr[i] = 1;
        return (T) _currentValue;
    }
}